/*
 * @Author: Salaing
 * @Date: 2024-08-04 15:51:56
 * @LastEditors: Salaing
 * @LastEditTime: 2024-08-31 22:34:59
 * @Description: 前端直传 七牛
 */
import React, { useEffect, useState } from 'react';
import $http from 'api';
import { Upload, Modal } from 'antd';
const UploadCompoment = ({ avatar, getNewAvatar }) => {
  const [token, setToken] = useState('');
  const [fileList, setFileList] = useState([]);
  const [previewImg, setpreviewImg] = useState([]);
  const [isShowModel, setIsShowModel] = useState(false);

  useEffect(() => {
    if (avatar) {
      setFileList([{ url: avatar }]);
      setpreviewImg(avatar);
    }
    _getToken();
  }, []);

  // 图片预览处理
  const handlePreview = () => {
    setIsShowModel(true);
  };

  const handleChange = (info) => {
    setFileList(info.fileList);
    if (info.file.status === 'done') {
      setpreviewImg('http://' + info.file.response.url);
      getNewAvatar('http://' + info.file.response.url);
      // if (previewImg || avatar) {
      //   _deletePreviewImg();
      // }
    }
  };

  // 关闭预览
  const handlePreClose = () => {
    setIsShowModel(false);
  };
  const _getToken = async () => {
    const { data } = await $http.getUploadToken({
      bucket: 'react-oa', //仓库名
      uploadUrl: 'shqjbje8x.hn-bkt.clouddn.com',
      accessKey: 'LaBsUmSe_yZGBk4aNJ4vQQCZVc_xEAAgDq977AXN', //- 公钥
      secretKey: 'f6pyVBlvTJcNv6dQAxs_oFPP9LtfSzwcoEOwuzDN', //- 私钥
    });
    setToken(data);
  };

  //- 删除之前的图片
  const _deletePreviewImg = async () => {
    const res = await $http.deleteFile({
      bucket: 'react-oa', //仓库名
      accessKey: 'LaBsUmSe_yZGBk4aNJ4vQQCZVc_xEAAgDq977AXN', //- 公钥
      secretKey: 'f6pyVBlvTJcNv6dQAxs_oFPP9LtfSzwcoEOwuzDN', //- 私钥
      fileName: previewImg ? previewImg : avatar,
    });
  };
  // 七牛空间要设置为公共的才能访问到图片
  return (
    <>
      <Upload
        action="https://up-z2.qiniup.com/"
        maxCount={1}
        listType="picture-card"
        data={{ token }}
        fileList={fileList}
        onPreview={handlePreview}
        onChange={handleChange}
      >
        选择图片
      </Upload>
      <Modal
        open={isShowModel}
        footer={null}
        closable={false}
        onCancel={handlePreClose}
      >
        <img style={{ width: '100%' }} src={previewImg} alt="" />
      </Modal>
    </>
  );
};

export default UploadCompoment;
